package com.xuelang.pipeline.app.pipeline;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xuelang.pipeline.app.pipeline.impl.PipelineWorkflowServiceImpl;
import com.xuelang.pipeline.app.resource.util.TektonUtil;
import com.xuelang.pipeline.app.resource.v1beta.pipeline.V1Beta1PipelineRun;
import com.xuelang.pipeline.client.pipeline.enums.ActionTypeEnum;
import com.xuelang.pipeline.client.pipeline.enums.ContainerStatusEnum;
import com.xuelang.pipeline.client.pipeline.enums.TaskInstanceEnum;
import com.xuelang.pipeline.client.pipeline.enums.TaskResultTypeEnum;
import com.xuelang.pipeline.domain.pipeline.Pipeline;
import com.xuelang.pipeline.domain.task.TaskInstance;
import io.kubernetes.client.openapi.models.V1ContainerStatus;
import io.kubernetes.client.openapi.models.V1Pod;

import java.time.OffsetDateTime;
import java.util.*;

/**
 * @author liuyuan.ly
 * @since 2024/8/21 14:18
 */
public interface TrackTaskService {

    /**
     * 容器状态转任务实例定义状态
     *
     * @param containerStatus
     * @return
     */
    default Integer getTaskStatus(String containerStatus) {
        Integer status;
        if (containerStatus.equals(ContainerStatusEnum.Succeeded.getKey())) {
            status = TaskInstanceEnum.success.getKey();
        } else if (containerStatus.equals(ContainerStatusEnum.Running.getKey())) {
            status = TaskInstanceEnum.running.getKey();
        } else if (containerStatus.equals(ContainerStatusEnum.NotReady.getKey())) {
            status = TaskInstanceEnum.notStart.getKey();
        } else if (containerStatus.equals(ContainerStatusEnum.Pending.getKey())) {
            status = TaskInstanceEnum.running.getKey();
        } else if (containerStatus.equals(ContainerStatusEnum.Failed.getKey())) {
            status = TaskInstanceEnum.failed.getKey();
        } else {
            status = TaskInstanceEnum.failed.getKey();
        }
        return status;
    }

    default String getTaskAction(TaskInstance taskInstance, String envId) {
        List<PipelineWorkflowServiceImpl.TaskOutput> actionList = JSON.parseArray(taskInstance.getAction(), PipelineWorkflowServiceImpl.TaskOutput.class);
        if (CollectionUtils.isEmpty(actionList)) {
            //为空首次才加入日志按钮，后续不处理。
            actionList = new ArrayList<>();
            PipelineWorkflowServiceImpl.TaskOutput taskOutput = getLogAction(taskInstance, envId);
            actionList.add(taskOutput);
        }
        //actionList不含logAction才加入
        return JSON.toJSONString(actionList);
    }


    default Date getEndTime(V1Pod v1Pod) {
        if (!v1Pod.getStatus().getPhase().equals(ContainerStatusEnum.Running.getKey())) {
            //非运行状态有结束时间
            OffsetDateTime finishedAt = null;
            if (v1Pod != null && v1Pod.getStatus() != null && v1Pod.getStatus().getContainerStatuses() != null && !v1Pod.getStatus().getContainerStatuses().isEmpty()) {
                //获取第一个容器的状态
                V1ContainerStatus containerStatus = v1Pod.getStatus().getContainerStatuses().get(v1Pod.getStatus().getContainerStatuses().size() - 1);
                if (containerStatus.getState() != null && containerStatus.getState().getTerminated() != null && containerStatus.getState().getTerminated().getFinishedAt() != null) {
                    finishedAt = containerStatus.getState().getTerminated().getFinishedAt();
                    return TektonUtil.getDate2offsetDate(finishedAt);
                }
            }
        }

        return null;
    }

    default PipelineWorkflowServiceImpl.TaskResultInfo getApproveTip(String taskInstanceCode) {
        List<Map<String, String>> data = new ArrayList<>();
        HashMap<String, String> noAccessMap = new HashMap<>();
        noAccessMap.put("buttonName", "验证不通过");
        noAccessMap.put("url", "/devops/pipelineInstance/approve/0/" + taskInstanceCode);
        noAccessMap.put("color", "red");
        data.add(noAccessMap);

        HashMap<String, String> accessMap = new HashMap<>();
        accessMap.put("buttonName", "验证通过");
        accessMap.put("url", "/devops/pipelineInstance/approve/1/" + taskInstanceCode);
        accessMap.put("color", "blue");
        data.add(accessMap);
        return PipelineWorkflowServiceImpl.TaskResultInfo.builder().type(TaskResultTypeEnum.invoke.getKey()).data(data).position("center").build();

    }

    default PipelineWorkflowServiceImpl.TaskOutput getLogAction(TaskInstance taskInstance, String envId) {
        PipelineWorkflowServiceImpl.TaskOutput taskOutput = new PipelineWorkflowServiceImpl.TaskOutput();
        taskOutput.setActionType(ActionTypeEnum.logButton.getKey());
        taskOutput.setActionUrl("/taskLog-stream?podName=" + taskInstance.getCode() + "&envId=" + envId + "&containerName=step-main");
        taskOutput.setActionName("查看日志");
        taskOutput.setIcon("log-icon");
        return taskOutput;
    }



    /**
     * 部署单处理
     */
    void deploymentUnitProcess(TaskInstance taskInstance, Pipeline pipeline);

    //    /**
//     * 跟踪运行中的任务
//     *
//     * @param pipelineRun
//     * @param pipeline
//     * @param
//     */
    void trackRunningPipeline(V1Beta1PipelineRun pipelineRun, Pipeline pipeline);
    //
//    /**
//     * 跟踪成功的任务
//     *
//     * @param pipelineRun
//     * @param pipeline
//     * @param
//     */
    void trackSuccessPipeline(V1Beta1PipelineRun pipelineRun, Pipeline pipeline);


    /**
     * 获取任务错误提示
     *
     * @param tip
     * @return
     */
    default PipelineWorkflowServiceImpl.TaskResultInfo getTaskTip(String tip) {
        List<Map<String, String>> data = new ArrayList<>();
        HashMap<String, String> tipMap = new HashMap<>();
        tipMap.put("tip", tip);
        data.add(tipMap);
        return PipelineWorkflowServiceImpl.TaskResultInfo.builder().type(TaskResultTypeEnum.errorTip.getKey()).data(data).position("center").build();
    }

}

